package com.作业.Day15;

import java.io.*;

public class Homework1 {
    public static void main(String[] args) {
        File file = new File("text1");

        // 1. 先读取文件内容（单独的try-with-resources块）
        String originalContent = "";
        try (FileReader fileReader = new FileReader(file);
             BufferedReader bufferedReader = new BufferedReader(fileReader)) {

            char[] cbuf = new char[40];
            int readLen = bufferedReader.read(cbuf);
            if (readLen != -1) {
                // 只保留实际读取的内容（排除空字符）
                originalContent = new String(cbuf, 0, readLen);
            }
            System.out.print("替代前: " + originalContent);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 2. 执行字符串替换
        String s1 = originalContent.replaceAll("\\{name}", "欧欧");
        String s2 = s1.replaceAll("\\{type}", "狗狗");
        String s3 = s2.replaceAll("\\{master}", "李伟");
        System.out.println("\n替代之后: " + s3);

        // 3. 再写入文件（单独的try-with-resources块）
        try (FileWriter writer = new FileWriter(file);
             BufferedWriter bufferedWriter = new BufferedWriter(writer)) {

            bufferedWriter.write(s3);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
